package com.freight.msg.controller;

import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.utils.PageUtil;
import com.freight.core.common.utils.ResultUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.common.vo.PageVo;
import com.freight.core.common.vo.Result;
import com.freight.core.common.vo.SearchVo;
import com.freight.core.entity.User;
import com.freight.core.service.UserRoleService;
import com.freight.core.service.UserService;
import com.freight.msg.entity.Message;
import com.freight.msg.entity.MessageSend;
import com.freight.msg.service.MessageSendService;
import com.freight.msg.service.MessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * @describe
 */
@Slf4j
@RestController
@Api(description = "消息内容管理接口")
@RequestMapping("/freight/message")
@Transactional
public class MsgMessageController {

    @Autowired
    private MessageService messageService;

    @Autowired
    private MessageSendService sendService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @RequestMapping(value = "/getByCondition", method = RequestMethod.GET)
    @ApiOperation(value = "多条件分页获取")
    public Result<Page<Message>> getByCondition(Message message,
                                                SearchVo searchVo,
                                                PageVo pageVo) {

        Page<Message> page = messageService.findByCondition(message, searchVo, PageUtil.initPage(pageVo));
        return new ResultUtil<Page<Message>>().setData(page);
    }

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取")
    public Result<Message> get(@PathVariable Long id) {
        Message message = messageService.get(id);
        return new ResultUtil<Message>().setData(message);
    }

//
//    @RequestMapping(value = "/keFuReMessage", method = RequestMethod.POST)
//    @ApiOperation(value = "客服回复消息")
//    public Result<Object> keFuReMessage(MessageReSendDto messageReSendDto) {
//        User u = securityUtil.getCurrUser();
//        Message message = messageService.get(messageReSendDto.getMessageId());
//        if (null != message && message.getUserId() != null) {
//            // 保存消息发送表
//            Message mm = new Message();
//            ObjectUtil.copyPropertiesIgnoreNull(messageReSendDto, mm);
//            mm.setTopicId(message.getTopicId());
//            mm.setUserId(u.getId());
//
//            Message m = messageService.save(mm);
//
//            List<MessageSend> messageSends = new ArrayList<>();
//            MessageSend ms = new MessageSend();
//            ms.setMessageId(m.getId());
//            ms.setUserId(m.getUserId());
//            ms.setCreateUserId(u.getId());
//            ms.setType(m.getType());
//            messageSends.add(ms);
//            // 指定用户
//            messagingTemplate.convertAndSendToUser
//                    (String.valueOf(m.getUserId()), "/queue/subscribe"
//                            , "您收到了新的消息");
//            sendService.saveOrUpdateAll(messageSends);
//        }
//
//        return ResultUtil.success("发送成功");
//    }
//
//    @RequestMapping(value = "/keFuMessage", method = RequestMethod.POST)
//    @ApiOperation(value = "客服消息留言消息")
//    public Result<Object> keFuMessage(MessageRoleDto messageDto) {
//        User u = securityUtil.getCurrUser();
//        if(messageDto.getUserId() == null){
//            messageDto.setUserId(u.getId());
//        }
//        Message message = new Message();
//        ObjectUtil.copyPropertiesIgnoreNull(messageDto, message);
//        // 保存消息发送表
//        message.setTopicId(SnowFlakeUtil.nextId().toString());
//        Message m = messageService.save(message);
//        List<MessageSend> messageSends = new ArrayList<>();
//        List<User> users = userRoleService.findUserByRoleName(CommonConstant.ROLE_KEFU);
//        for (User user : users) {
//            MessageSend ms = new MessageSend();
//            ms.setMessageId(m.getId());
//            ms.setUserId(user.getId());
//            ms.setCreateUserId(m.getUserId());
//            ms.setType(message.getType());
//            messageSends.add(ms);
//            // 指定用户
//            messagingTemplate.convertAndSendToUser
//                    (String.valueOf(user.getId()), "/queue/subscribe"
//                            , "您收到了新的消息");
//        }
//        sendService.saveOrUpdateAll(messageSends);
//        return ResultUtil.success("发送成功");
//    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加消息")
    public Result<Object> addMessage(Message message) {

        Message m = messageService.save(message);
        // 保存消息发送表
        List<MessageSend> messageSends = new ArrayList<>();
        if (CommonConstant.MESSAGE_RANGE_ALL.equals(message.getRange())) {
            // 全体
            List<User> allUser = userService.getAll();
            allUser.forEach(u -> {
                MessageSend ms = new MessageSend();
                ms.setMessageId(m.getId());
                ms.setUserId(u.getId());
                ms.setCreateUserId(m.getUserId());
                messageSends.add(ms);
            });
            // 推送
            messagingTemplate.convertAndSend("/topic/subscribe", "您收到了新的系统消息");
        } else {
            // 指定用户
            for (Long id : message.getUserIds()) {
                MessageSend ms = new MessageSend();
                ms.setMessageId(m.getId());
                ms.setUserId(id);
                messageSends.add(ms);
                // 指定用户
                messagingTemplate.convertAndSendToUser(String.valueOf(id), "/queue/subscribe", "您收到了新的消息");
            }
        }
        sendService.saveOrUpdateAll(messageSends);
        return ResultUtil.success("添加成功");
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ApiOperation(value = "编辑消息")
    public Result<Object> editMessage(Message message) {

        Message m = messageService.update(message);
        return ResultUtil.success("编辑成功");
    }

    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @ApiOperation(value = "删除消息")
    public Result<Object> delMessage(@RequestParam Long[] ids) {

        for (Long id : ids) {
            messageService.delete(id);
            // 删除发送表
            sendService.deleteByMessageId(id);
        }
        return ResultUtil.success("编辑成功");
    }
}
